from typing import List

import pydantic
from sqlalchemy import delete, insert, select

from forward.api.admin.schemas.setting import (
    SettingHotSearchInSchema,
    SettingHotSearchOutSchema,
)
from forward.dependencies.database import db
from forward.model.tables import HotSearchModel
from forward.utils.config import ConfigUtil


class SettingSearchService:
    """热门搜索服务实现类"""

    async def detail(self) -> dict:
        """热门搜索详情"""
        is_hot_search = await ConfigUtil.get_val("search", "isHotSearch", "0")
        is_hot_search = (
            int(is_hot_search)
            if is_hot_search is not None and is_hot_search.isdigit()
            else 0
        )
        objs = await db.fetch_all(
            select(HotSearchModel).order_by(HotSearchModel.sort.desc())
        )
        return {
            "is_hot_search": is_hot_search,
            "list": [
                SettingHotSearchOutSchema.model_validate(i, from_attributes=True)
                for i in objs
            ],
        }

    async def save(self, hot_search_in: SettingHotSearchInSchema):
        """热门搜索新增"""
        await ConfigUtil.set("search", "isHotSearch", str(hot_search_in.is_hot_search))
        await db.execute(delete(HotSearchModel).where(HotSearchModel.id > 0))
        await db.execute(
            insert(HotSearchModel).values(hot_search_in.model_dump()["list"])
        )

    @classmethod
    async def instance(cls):
        """实例化"""
        return cls()
